package com.oazon.moco.lan.handler;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.oazon.moco.bean.HttpMsgBodyBean;
import com.oazon.moco.lan.core.AbsHttpMsgHandler;
import com.oazon.moco.lan.core.controldriver.bean.ControlDriver;
import com.oazon.moco.lan.core.controldriver.cache.ControlDriverCache;
import com.oazon.moco.lan.core.http.bean.JsonMessageType;
import com.oazon.moco.lan.core.http.bean.RequestOperation;
import com.oazon.moco.lan.core.http.bean.ResponseSubscribe;
import com.oazon.moco.lan.core.http.bean.UnSubscribe;
import com.oazon.moco.lan.util.LanServer;
import com.oazon.moco.link.core.LinkSDK;
import com.oazon.moco.link.core.source.LanEventSource;

public class SubscribeHandler extends AbsHttpMsgHandler {

	@Override
	public void doBusiness(HttpMsgBodyBean bean) {
		if (!RequestOperation.OPERATION_SUBSCRIBE.equals(bean.getOperation())) {
			return;
		}

		if (JsonMessageType.SUBSCRIBE.toString().equals(bean.getType())) {
			subcribe(bean);

		} else if (JsonMessageType.UNSUBSCRIBE.toString()
				.equals(bean.getType())) { // 取消订阅
			unSubscribe(bean);

		}

	}

	private void unSubscribe(HttpMsgBodyBean bean) {
		
		UnSubscribe subscribe = JSON.parseObject(bean.getData(),
				UnSubscribe.class);
		String strUuid = subscribe.getUuid();
		
		ControlDriver controlDriver = ControlDriverCache.getInstance()
				.findControlDriverByUuid(strUuid);

		if (ControlDriverCache.getInstance().findControlDriverByUuid(
				controlDriver.getUuid()) == null) {
			return;
		}

		if (ControlDriverCache.getInstance().deleteControlDriverByUuid(
				strUuid)) {
			LanServer
					.responseResult(bean.getType(), 0, null, bean.getCtx());

			LinkSDK.getInstance().unsubscribe(
					new LanEventSource(bean.getCtx(), null), controlDriver);
		} else {
			LanServer.responseResult(bean.getType(), -1, null,
					bean.getCtx());
		}
	} 

	private void subcribe(HttpMsgBodyBean bean) {
		
		ControlDriver controlDriver = JSON.parseObject(bean.getData(),
				ControlDriver.class);
		controlDriver.setCreateTime(new Date());

		if (ControlDriverCache.getInstance().insertControlDriver(
				controlDriver)) {

			ResponseSubscribe responseSubscribe = new ResponseSubscribe();
			responseSubscribe.getSid();
			responseSubscribe.setExpiry(controlDriver.getExpiry());
			responseSubscribe.setUuid(LinkSDK.getUUid());
			LinkSDK.getInstance().subscribe(
					new LanEventSource(bean.getCtx(), null), controlDriver);
			LanServer.responseResult(bean.getType(), 0, responseSubscribe,
					bean.getCtx());
		} else {
			LanServer.responseResult(bean.getType(), -1, null,
					bean.getCtx());
		}
	}
}
